package com.california.payopenapi.exception;

import com.california.payopenapi.common.ServerResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BeanPropertyBindingResult;
import org.springframework.validation.BindException;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.List;

/**
 * @Description:
 * @author: KeyboardMan
 * @Date: Create in 2018-12-09:23:34
 */
@Slf4j
@RestControllerAdvice
public class SystemExceptionHandler {

    @ExceptionHandler
    public ServerResponse handler(Exception e) {
         // 判断是否是参数校验出错
        if (e instanceof MethodArgumentNotValidException) {
            log.error( "参数校验异常  :" +  e);
            MethodArgumentNotValidException c = (MethodArgumentNotValidException) e;
            List<ObjectError> errors = c.getBindingResult().getAllErrors();
            StringBuffer errorMsg = new StringBuffer();
            errors.stream().forEach(x -> errorMsg.append(x.getDefaultMessage()));
            return ServerResponse.createByErrorMessage(errorMsg.toString());
        }

        if (e instanceof BindException) {
            log.error( "参数校验异常  :" +  e);
            BindException bindException = (BindException) e;
            List<ObjectError> errors = bindException.getBindingResult().getAllErrors();
            StringBuffer errorMsg = new StringBuffer();
            errors.stream().forEach(x -> errorMsg.append(x.getDefaultMessage()));
            return ServerResponse.createByErrorMessage(errorMsg.toString());
        }

        if (e instanceof SystemException) {
            log.error( "系统自定义异常  :" +  e);
            return ServerResponse.createByErrorMessage(((SystemException) e).getErrMsg());
        }
        e.printStackTrace();
        return null;
    }
}
